import moment, { Moment } from 'moment'
import i18n from 'i18n-js'
import { getItemForPk, IProduct } from '@/config/product'
import { IServiceSchedule, IBaseServiceSchedule, IEditParamSchedule, IAddParamSchedule } from './scheduleApi'

let targetDevice: IDevice | undefined
let productConifg: IProduct | undefined

const noneString = 'none'

export enum WeekDayEnum {
  Mon = 'mon',
  Tues = 'tue',
  Wednes = 'wed',
  Thurs = 'thu',
  Fri = 'fri',
  Satur = 'sat',
  Sun = 'sun'
}

// 方便排序使用
export const weekMap = {
  [WeekDayEnum.Mon]: 1 << 0,
  [WeekDayEnum.Tues]: 1 << 1,
  [WeekDayEnum.Wednes]: 1 << 2,
  [WeekDayEnum.Thurs]: 1 << 3,
  [WeekDayEnum.Fri]: 1 << 4,
  [WeekDayEnum.Satur]: 1 << 5,
  [WeekDayEnum.Sun]: 1 << 6,
}

// 星期数据列表
export const weekList = [
  { label: 'Monday', value: WeekDayEnum.Mon },
  { label: 'Tuesday', value: WeekDayEnum.Tues },
  { label: 'Wednesday', value: WeekDayEnum.Wednes },
  { label: 'Thursday', value: WeekDayEnum.Thurs },
  { label: 'Friday', value: WeekDayEnum.Fri },
  { label: 'Saturday', value: WeekDayEnum.Satur },
  { label: 'Sunday', value: WeekDayEnum.Sun },
];

interface ITimeObject {
  hour: number // 小时
  minute: number // 分钟
}

const isExpire = (item: ISchedule) => {
  console.log('isExpire', item)
  if (item.sourceData?.repeat === 'none') {

    const now = moment()
    if (item.dateObj.isBefore(now)) {
      return true
    }
  };
  return false;
}
// 列表接口返回的数据格式
export interface ISchedule extends IBaseServiceSchedule {
  id?: string;
  sourceData?: IServiceSchedule // 存放原来服务端返回的数据
  // 以下是处理后的字段，方便拿来操作和显示使用
  repeatArray: Set<WeekDayEnum> // repeat处理后的，如果是[]，代表不重复
  dateObj: Moment // date处理后的
  timeObj: ITimeObject // time 处理后的字段
  repeatText?: string // 重复文案
  functionText?: string // 功能文案
}

function getWeekdayText(week: WeekDayEnum) {
  const weekday = weekList.find((i) => i.value === week);
  return i18n.t(weekday?.label ?? '');
}

/**
 * 定时的repeat字符串转化为星期数组
 * @param repeatStr 定时的repeat字符串 
 * @returns WeekDay枚举数组
 */
function weekStringToWeekArray(repeatStr: string) {
  if (!repeatStr || repeatStr.length < 1 || repeatStr === noneString) {
    return new Set<WeekDayEnum>();
  }
  const arr = repeatStr.split(',')
  const weekArray: Set<WeekDayEnum> = new Set()
  arr.forEach((i) => {
    switch (i) {
      case WeekDayEnum.Mon:
        weekArray.add(WeekDayEnum.Mon)
        break;
      case WeekDayEnum.Tues:
        weekArray.add(WeekDayEnum.Tues)
        break;
      case WeekDayEnum.Wednes:
        weekArray.add(WeekDayEnum.Wednes)
        break;
      case WeekDayEnum.Thurs:
        weekArray.add(WeekDayEnum.Thurs)
        break;
      case WeekDayEnum.Fri:
        weekArray.add(WeekDayEnum.Fri)
        break;
      case WeekDayEnum.Satur:
        weekArray.add(WeekDayEnum.Satur)
        break;
      case WeekDayEnum.Sun:
        weekArray.add(WeekDayEnum.Sun)
        break;
      default:
        break;
    }
  })
  return weekArray
}

/**
 * 定时时间字符转化为ITimeObject
 * @param timeString 定时时间字符，格式“02:30”
 * @returns 返回处理后的ITimeObject，hour和minute默认为0
 */
function handleTimeString(timeString: string) {
  const time: ITimeObject = { hour: 0, minute: 0 }
  if (timeString && timeString.length > 0) {
    const arr = timeString.split(':')
    if (arr.length > 0) {
      time.hour = parseInt(arr[0], 10)
    }
    if (arr.length > 1) {
      time.minute = parseInt(arr[1], 10)
    }
  }
  return time
}

function formatNumber(num: number) {
  return num.toString().padStart(2, '0')
}

export function getTimeText(time: ITimeObject) {
  return `${formatNumber(time.hour)}:${formatNumber(time.minute)}`
}

export function getRepeatText({ schedule, isFocus = false }: { schedule: ISchedule, isFocus?: boolean }) {
  if (!schedule.repeatText || isFocus) {
    if (schedule.repeatArray.size === 7) {
      schedule.repeatText = i18n.t('EVERY_DAY');
    } else if (schedule.repeatArray.size === 0) {
      schedule.repeatText = i18n.t('ONLY_ONCE');
      if (schedule.sourceData?.date) {
        schedule.repeatText += ` ${schedule.sourceData?.date}`
      }
    } else {
      const textArr: string[] = []
      schedule.repeatArray.forEach((week) => {
        textArr.push(getWeekdayText(week))
      })
      schedule.repeatText = textArr.join(' ')
    }
    console.log('getRepeatText', isFocus, schedule.repeatText)
  }
  return schedule.repeatText
}

function handUTCTimeToLocalTime({ date, time }: { date: string, time: string }) {
  const utcOffset = moment().utcOffset();
  const localTime = moment(date + time, 'YYYY-MM-DD HH:mm').add(utcOffset, 'minutes');
  return localTime
}

// 将服务端返回的数据转化为 ISchedule
export function hanldeServiceSchedule(schedule: IServiceSchedule): ISchedule {
  const loaclTime = handUTCTimeToLocalTime(schedule)
  const info = {
    ...schedule,
    repeatArray: weekStringToWeekArray(schedule.repeat),
    dateObj: loaclTime,
    timeObj: { hour: loaclTime.hour(), minute: loaclTime.minute() },
    sourceData: schedule,
  }
  const expire = isExpire(info)
  if (expire) {
    info.enabled = false;
  }
  return info;
}

export function setDevice(device: IDevice) {
  targetDevice = device
  productConifg = getItemForPk(device.productKey)
}

export function getDevice() {
  return targetDevice
}

export function getProductConfig() {
  return productConifg!
}
export function test() {
  console.log('test', weekStringToWeekArray('mon,sat'))
}


// ========= 本地数据转服务端 ==========

function getRepeatString(repeatArray: Set<WeekDayEnum>) {
  if (repeatArray.size < 1) {
    return noneString
  }
  return Array.from(repeatArray).join(',')
}

export function scheduleToServiceSchedule(schedule: ISchedule): IAddParamSchedule | IEditParamSchedule {
  const repeatStr = getRepeatString(schedule.repeatArray)
  const now = moment()
  // 如果日期已经过去了，就追加一天
  schedule.dateObj.hours(schedule.timeObj.hour);
  schedule.dateObj.minutes(schedule.timeObj.minute);

  if (schedule.dateObj.isBefore(now)) {
    schedule.dateObj.add(1, 'day')
  }
  const date = moment(schedule.dateObj)
  date.hour(schedule.timeObj.hour)
  date.minute(schedule.timeObj.minute)
  const UTCTime = moment.utc(date)
  return {
    ...schedule,
    repeat: repeatStr,
    date: UTCTime.format('YYYY-MM-DD'),
    time: UTCTime.format('HH:mm'),
  }
}
















